from django.shortcuts import render, HttpResponse, redirect, reverse
from django.http import JsonResponse
from django.contrib.auth.base_user import check_password
from django.contrib.auth.models import Group
from django.views.decorators.http import require_POST
import json
from django.db.models import Q
from django.contrib.auth.decorators import login_required

from xadmin.models import UserProfile, UserGroup, GroupPermission
from xadmin.forms import UserProfileForm, UserGroupForm
from xadmin import permission


@login_required
def modifyPassword(request, userid):
    if request.method == 'GET':
        return render(request, 'xadmin/userprofile/modifypassword.html')
    else:
        password = request.POST.get('password')
        newpassword = request.POST.get('newpassword')
        newpassword1 = request.POST.get('newpassword1')
        context = {
            'password': password,
            'newpassword': newpassword,
        }
        if newpassword != newpassword1:
            context['error'] = '两次输入的密码不一致'
            return render(request, 'xadmin/userprofile/modifypassword.html', context)
        user = UserProfile.objects.get(id=userid)
        if user:
            if check_password(password, user.password):
                user.set_password(newpassword)
                user.save()
                return HttpResponse('<script>parent.layer.alert("修改成功", function(){parent.layer.closeAll();})</script>')
            else:
                context['error'] = '原密码不正确'
                return render(request, 'xadmin/userprofile/modifypassword.html', context)
        else:
            context['error'] = '用户不存在'
            return render(request, 'xadmin/userprofile/modifypassword.html', context)


@login_required
def user_list(request):
    siteid = request.GET.get('siteid', '1')
    mbx = ('系统配置', '用户')
    user_queryset = UserProfile.objects.filter(~Q(username='admin'), site_id=siteid)
    context = {
        'siteid': siteid,
        'user_list': user_queryset,
        'mbx': mbx
    }
    return render(request, 'xadmin/userprofile/userlist.html', context)


@login_required
def user_add(request):
    siteid = request.GET.get('siteid')
    groups = UserGroup.objects.filter(site_id=siteid)
    mbx = ('系统配置', '用户', '添加用户')
    if request.method == 'GET':
        user_form = UserProfileForm.UserProfileForm()

        context = {
            'user_form': user_form,
            'siteid': siteid,
            'mbx': mbx,
            'groups': groups
        }
        return render(request, 'xadmin/userprofile/add.html', context)
    else:
        user_form = UserProfileForm.UserProfileForm(request.POST)
        context = {
            'siteid': siteid,
            'mbx': mbx,
            'user_form': user_form,
            'groups': groups,
        }
        groups_ids = request.POST.getlist('groups')

        if user_form.is_valid():
            try:
                new_user = user_form.save(commit=False)
                new_user.set_password(new_user.password)
                new_user.site_id = siteid
                new_user.save()
                new_user.user_group.add(*groups_ids)

                return redirect(reverse('userlist') + '?siteid=' + siteid)
            except Exception as e:
                context['error'] = '写入数据库时出现错误'
                return render(request, 'xadmin/userprofile/add.html', context)
        else:
            error = user_form.errors
            context['error'] = error
            return render(request, 'xadmin/userprofile/add.html', context)


@login_required
def user_edit(request):
    siteid = request.GET.get('siteid')
    groups = UserGroup.objects.filter(site_id=siteid)
    userid = request.GET.get('userid')
    user = UserProfile.objects.get(id=userid)
    user_form = UserProfileForm.UserProfileEditFrom(instance=user)
    mbx = ('系统配置', '用户', '编辑用户')
    context = {
        'siteid': siteid,
        'groups': groups,
        'mbx': mbx,
        'user': user,
        'user_form': user_form,
    }
    if request.method == 'GET':
        return render(request, 'xadmin/userprofile/add.html', context)
    else:
        user_form = UserProfileForm.UserProfileEditFrom(request.POST, instance=user)
        context = {
            'siteid': siteid,
            'mbx': mbx,
            'user_form': user_form,
            'groups': groups,
            'user':user,
        }
        groups_ids = request.POST.getlist('groups')

        if user_form.is_valid():

            try:
                new_user = user_form.save()
                user.user_group.clear()
                new_user.user_group.add(*groups_ids)
                return redirect(reverse('userlist') + '?siteid=' + siteid)
            except Exception as e:
                context['error'] = '写入数据库时出现错误'
                return render(request, 'xadmin/userprofile/add.html', context)
        else:
            error = user_form.errors
            context['error'] = error
            return render(request, 'xadmin/userprofile/add.html', context)


@login_required
@require_POST
def user_del(request):
    userid = request.POST.get('userid')
    mess = {}
    try:
        user = UserProfile.objects.get(id=userid)
        if user.is_superuser:
            super_users = UserProfile.objects.filter(is_superuser=True, is_active=True)
            if user in super_users and len(super_users) == 0 or user.is_superuser:
                mess['status'] = '500'
                mess['msg'] = '超级管理员帐户不允许删除'
                return JsonResponse(mess)
        user.delete()
        mess['status'] = '200'
        mess['message'] = '删除成功'
        return JsonResponse(mess)
    except Exception as e:
        print(e)
        mess['status'] = '500'
        mess['message'] = '删除失败'
        return JsonResponse(mess)


@login_required
def group_list(request):
    siteid = request.GET.get('siteid')
    mbx = ('系统配置', '角色')
    context = {
        'siteid': siteid,
        'mbx': mbx
    }
    groups = UserGroup.objects.filter(site_id=siteid)
    context['groups'] = groups
    return render(request, 'xadmin/userprofile/grouplist.html', context)


def group_add(request):
    siteid = request.GET.get('siteid')
    mbx = ('系统配置', '角色', '新增角色')
    if request.method == 'GET':
        group_form = UserGroupForm.UserGroupForm()
        context = {
            'siteid': siteid,
            'mbx': mbx,
            'group_form': group_form,
            'permissions': permission.permission_dic
        }
        return render(request, 'xadmin/userprofile/groupadd.html', context)
    else:
        usergroup_form = UserGroupForm.UserGroupForm(request.POST)
        context = {
            'siteid': siteid,
            'mbx': mbx,
            'group_form': usergroup_form,
        }
        if usergroup_form.is_valid():
            new_group = usergroup_form.save(commit=False)
            new_group.site_id = siteid
            new_group.save()
            #添加权限
            perjson = request.POST.get('perjson')
            permissions_dic = json.loads(perjson)
            for k, v in permissions_dic.items():
                for i in v:
                    GroupPermission.objects.create(group_id=new_group.id, permission_type=k, permission_slug=i, site_id=siteid)
            return redirect(reverse('grouplist') + '?siteid=' + siteid)
        else:
            error = usergroup_form.errors
            context['error'] = error
            return render(request, 'xadmin/userprofile/groupadd.html', context)


@login_required
def group_edit(request):
    siteid = request.GET.get('siteid')
    groupid = request.GET.get('groupid')
    group_obj = UserGroup.objects.get(id=groupid)
    mbx = ('系统配置', '角色', '编辑角色')
    context = {
        'siteid': siteid,
        'group': group_obj,
        'permissions': permission.permission_dic,
        'mbx': mbx
    }
    if request.method == 'GET':
        group_form = UserGroupForm.UserGroupForm(instance=group_obj)
        has_permission = GroupPermission.objects.filter(site_id=siteid, group_id=groupid)
        permission_json = {}
        for perm in has_permission:
            if perm.permission_type in permission_json:
                if perm.permission_slug in permission_json[perm.permission_type]:
                    pass
                else:
                    permission_json[perm.permission_type].append(perm.permission_slug)
            else:
                permission_json[perm.permission_type] = [perm.permission_slug]
        permission_json = json.dumps(permission_json)
        context['group_form'] = group_form
        context['perm_json'] = permission_json
        return render(request, 'xadmin/userprofile/groupadd.html', context)
    else:
        usergroup_form = UserGroupForm.UserGroupForm(request.POST, instance=group_obj)
        context['group_form'] = usergroup_form
        if usergroup_form.is_valid():
            new_group = usergroup_form.save()
            #添加权限
            perjson = request.POST.get('perjson')
            permissions_dic = json.loads(perjson)
            GroupPermission.objects.filter(site_id=siteid, group_id=groupid).delete()
            for k, v in permissions_dic.items():
                for i in v:
                    GroupPermission.objects.create(group_id=new_group.id, permission_type=k, permission_slug=i, site_id=siteid)
            return redirect(reverse('grouplist') + '?siteid=' + siteid)
        else:
            error = usergroup_form.errors
            context['error'] = error
            return render(request, 'xadmin/userprofile/groupadd.html', context)


@login_required
@require_POST
def group_del(request):
    groupid = request.POST.get('groupid')
    mess = {}
    try:
        UserGroup.objects.get(id=groupid).delete()
        #删除关于该角色的权限
        GroupPermission.objects.filter(group_id=groupid).delete()
        mess['status'] = '200'
        mess['msg'] = '删除成功'
    except:
        mess['status'] = '500'
        mess['msg'] = '删除失败'
    return JsonResponse(mess)
